﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;

namespace SystemAPi.JWT
{
    public class JwtHelper
    {
        public JwtHelper()
        {
            //Configuration = configuration;
        }
        /// <summary>
        /// 配置属性
        /// </summary>
        public IConfiguration Configuration { get; }
        /// <summary>
        /// 生成Token
        /// </summary>
        /// <returns></returns>
        public string GenerateToken(string Name,string Userid)
        {
            //var jwtConfig = Configuration.GetSection("Jwt");
            //秘钥，就是标头，这里用Hmacsha256算法，需要256bit的密钥
            // string secret =jwtConfig.GetValue<string>("Secret")
            string secret = "yuanfengchao123456789";
            var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)), SecurityAlgorithms.HmacSha256);
            //Claim，JwtRegisteredClaimNames中预定义了好多种默认的参数名，也可以像下面的Guid一样自己定义键名.
            //ClaimTypes也预定义了好多类型如role、email、name。Role用于赋予权限，不同的角色可以访问不同的接口
            //相当于有效载荷
            List<Claim> baseClaims = new List<Claim>{
                new Claim(JwtRegisteredClaimNames.Iss,"yfc"),
                new Claim(JwtRegisteredClaimNames.Aud,"client"),
                new Claim("Guid",Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Role,"admin"),
             };
           
            SecurityToken securityToken = new JwtSecurityToken(
                signingCredentials: securityKey,
                expires: DateTime.Now.AddDays(1),//过期时间
                claims: baseClaims
            );
            //生成jwt令牌
            return new JwtSecurityTokenHandler().WriteToken(securityToken);
        }
    }
}